package com.guass.nettyprotostuff.rpc.server.handler;

import com.guass.nettyprotostuff.rpc.MsgDecoder;
import com.guass.nettyprotostuff.rpc.MsgEncoder;
import com.guass.nettyprotostuff.rpc.common.TypeData;
import com.guass.nettyprotostuff.service.RpcService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author guass
 */
public class ChildChannelHandler extends ChannelInitializer<Channel> {

    private long readerIdleTime;

    private RpcService rpcService;

    public ChildChannelHandler(long readerIdleTime) {
        this.readerIdleTime = readerIdleTime;
    }

    public ChildChannelHandler(long readerIdleTime, RpcService rpcService) {
        this.readerIdleTime = readerIdleTime;
        this.rpcService = rpcService;
    }

    @Override
    protected void initChannel(Channel channel) throws Exception {
        NodesChannelHandler nodesChannelHandler = new NodesChannelHandler(rpcService);

        ByteBuf byteBuf = Unpooled.copiedBuffer(TypeData.DELIMITER.getBytes());
        //超过30分钟未收到客户端消息则自动断开客户端连接

        channel.pipeline().
        addLast("idleStateHandler",
                new IdleStateHandler(readerIdleTime, 0, 0, TimeUnit.MINUTES))
                .addLast(new DelimiterBasedFrameDecoder(1024,byteBuf))
                .addLast(new MsgDecoder())
                .addLast(new MsgEncoder())
                .addLast(nodesChannelHandler);

    }
}
